import json
import os
import uuid
from datetime import datetime

import pytz
from flask import Flask, Blueprint, Response, request
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from app.common.commonMessage import CommonMassages
from app.config.db import DBUtils
from app.config.jsonEncoder import CustomJSONEncoder

from app.model.SysReportConfigModel import SysReportConfigModel
from app.model.SysReportModel import SysReportModel

from app.service.SysReportService import SysReportService
from app.service.SysReportConfigService import SysReportConfigService
from app.service.reportGenerationService import ReportGenerationService

app = Flask(__name__)
# 创建蓝图
sys_report_bp = Blueprint('sys_report_controller', __name__, url_prefix='/kshx')

# 文件绝对路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 报告模板路径
report_tmp_path = os.path.join(project_root, 'static', 'tmp', 'kshx_tpl.docx')
# 图表生成保存路径
report_chart_path = os.path.join(project_root, 'static', 'chart')
# 下载路径
download_url = "http://192.168.1.182:9000/static/output/"

sysReport = SysReportService()
sysReportConfig = SysReportConfigService()
reportGeneration = ReportGenerationService()

# 获取session
db_utils = DBUtils()
session = db_utils.get_session()

@sys_report_bp.route('/report_generation', methods=['GET'])
@jwt_required()
def report_generation():
    # 获取公司名称
    company_name = request.args.get('company_name')
    # year = request.args.get('year')
    # start_date = request.args.get('start_date')
    # end_date = request.args.get('end_date')
    year = datetime.now().year
    start_date = f'{year}-01-01'
    end_date = datetime.now(pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d')
    # 文件名称
    file_name = f"{company_name}.docx"
    # 报告生成保存基础路径
    report_save_path = os.path.join(project_root, 'static', 'output', file_name)
    data = reportGeneration.generationReport(session, report_tmp_path, report_chart_path, report_save_path, company_name, year, start_date, end_date)
    if data.get("result") > 0:
        file_uuid = str(uuid.uuid4().hex)
        user_data = get_jwt_identity()
        sysReportModel = SysReportModel()
        sysReportModel.ID = str(uuid.uuid4().hex)
        sysReportModel.COMPANY_NAME = company_name
        sysReportModel.CREATE_USER = user_data['username']
        # sysReportModel.CREATE_USER = "张三"
        sysReportModel.CREATE_TIME = datetime.now(pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
        sysReportModel.FILE_UUID = file_uuid
        sysReportModel.FILE_NAME = file_name
        sysReportModel.FILE_URL_WORD = download_url + file_name
        sysReportModel.IS_DELETE = 0
        sysReport.insert_data(session, sysReportModel)
        for key,value in data.get("content").items():
            sysReportConfigModel = SysReportConfigModel()
            sysReportConfigModel.ID = str(uuid.uuid4().hex)
            sysReportConfigModel.REPORT_ID = file_uuid
            sysReportConfigModel.REPORT_KEY = key
            sysReportConfigModel.REPORT_VALUE = json.dumps(value, ensure_ascii=False, default=str)
            sysReportConfigModel.CREATE_DATE = datetime.now(pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d')
            sysReportConfigModel.IS_DELETE = 0
            sysReportConfig.insert_data(session, sysReportConfigModel)
        respResult = {
            "code": 200,
            "data": file_uuid,
            "message": CommonMassages. REPORT_GENERATION_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.REPORT_GENERATION_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False, default=str)
    return Response(resp_data, content_type='application/json')